#include <iostream>
#include <unistd.h>
#include<sys/types.h>
#include <cstring>
#include<sys/wait.h>

#define NUM 1024
using namespace std;

void WriteTo(int wfd)
{
    // 构建发送字符串
    string s = "I am child";
    pid_t self = getpid();
    int num = 0;
    char buffer[NUM];

    while(true) {
        // buffer[0] = 0;      // 字符串清空,目的是为了告诉阅读代码的人,我把这个数组当成字符串了,没有什么实际意义,去掉也可以
        // snprintf(buffer, sizeof(buffer), "%s-%d-%d\n", s.c_str(), self, num++);
        // cout<<buffer;
        // 发送/写给父进程
        // write(wfd, buffer, strlen(buffer));
        write(wfd, "a", 1);
        num++;
        sleep(1);
        // cout<<num << endl;
        if(num == 5)
            break;
    }
}

void ReadFrom(int rfd)
{
    char buffer[NUM] = {0};
    while(true) {
        // sleep(50);
        size_t n = read(rfd, buffer, sizeof(buffer));       // 这里是sizeof,因为read的时候不知道文件有多少数据,但是我们接收数据的大小就只有数组那么大，所以要读最大值
        if(n > 0) {
            buffer[n] = 0;  // 0 == '\0'
            cout << "father[" << getpid() << "] get a message: " << buffer;
        }
        cout << n << endl;
    }
}
int main()
{
    int pipefd[2] = {0};
    int ret = pipe(pipefd);

    if(ret == -1)    return 1;

    // cout << "pipefd[0]:" << pipefd[0] << " pipefd[1]:" << pipefd[1] << endl;
    pid_t id = fork();

    if(id == -1)    return 2;

    // 我们想让子进程写,父进程读
    if(id == 0) {
        // 子进程,关闭读的文件描述符
        close(pipefd[0]);

        // IPC code
        WriteTo(pipefd[1]);

        // 关闭资源
        close(pipefd[1]);
        exit(0);
    }
    // 父进程,关闭写的文件描述符
    close(pipefd[1]);

    // IPC code
    ReadFrom(pipefd[0]);

    // 进程等待
    pid_t wRet = waitpid(id, nullptr, 0);
    if(wRet == -1)  return 3;

    close(pipefd[0]);
    return 0;
}